package com.internetplus.webcore.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.internetplus.webcore.entity.Product;
import com.internetplus.webcore.mapper.ProductMapper;
import com.internetplus.webcore.response.CodeMsg;
import com.internetplus.webcore.response.Result;
import com.internetplus.webcore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {

 @Autowired
 private ProductMapper productMapper;


    @Override
    public Result findAll(int pageNum, int pageSize){

     PageHelper.startPage(pageNum,pageSize);
     PageInfo pageInfo = new PageInfo(productMapper.getAllProduct());

    List<Product> list = pageInfo.getList();

    if (list.isEmpty()) {
     return Result.error(CodeMsg.NOT_DATA_FOUND);
    }

    return Result.success(pageInfo);
    }


    @Override
    public Result findTargetById(int productid){

        List<Product> list = productMapper.findTargetProduct(productid);

        System.out.println(list.toString());

     if (list.isEmpty()) {
      return Result.error(CodeMsg.NOT_DATA_FOUND);
     }

     return Result.success(list);
    }


    @Override
    public Result findTargetByUserId(int userid){

        List<Product> list = productMapper.findTargetProductUserid(userid);

        System.out.println(list.toString());

        if (list.isEmpty()) {
            return Result.error(CodeMsg.NOT_DATA_FOUND);
        }

        return Result.success(list);
    }


    @Override
    public Result saveProduct(Product product){

     productMapper.updataProduct(product);
     return Result.success(null);

    }

    @Override
    public Result addProduct(Product product){
       productMapper.addProduct(product);
       return Result.success(null);
    }


    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackForClassName = "Exception")
    @Override
    public Result deleteProduct(List list) {

        try {
            int result = productMapper.deleteProduct(list);
            if (result != list.size()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Result.error(CodeMsg.DELETE_FAIL);
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error(CodeMsg.DELETE_FAIL);
        }

        return Result.success(null);
    }

}
